/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package axil.stdlib.collection.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.etc.Cloned;
import axil.etc.ConditionallyImmutable;
import axil.framework.type.Added;
import axil.framework.type.Subtracted;
import axil.stdlib.core.type.Nil;

import java.util.HashSet;
import java.util.Iterator;

import static axil.framework.Functions.axil;
import static axil.framework.Functions.error;


/**
 * An Axil implementation of a set.
 */
public class AxilSet<T extends AxilObject> extends AxilCollection<T>
	implements Cloned<AxilSet<T>>, ConditionallyImmutable<AxilSet<T>>, Added,
	Subtracted {
	public static final AxilType type = AxilSet_Type.object;
	public static final AxilSet empty = new AxilSet();

	private final HashSet<T> set;
	private boolean immutable;


	public AxilSet() {
		set = new HashSet<T>();
	}


	public AxilSet(T... objects) {
		this();
		for (T v : objects) {
			set.add(v);
		}
	}


	AxilSet(HashSet<T> values) {
		this.set = values;
	}


	private AxilSet(AxilSet<T> other) {
		this.set = (HashSet<T>)other.set.clone();
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Tell if this collection contains the value (not the key) given.
	 */
	public boolean has(AxilObject object) {
		return set.contains(object);
	}


	public boolean contains(T object) {
		return set.contains(object);
	}


	public AxilSet<T> put(T object) {
		edit();
		AxilSet<T> s = new AxilSet<T>(this);
		s.set.add(object);
		return s;
	}


	public AxilSet<T> put(AxilCollection<T> objects) {
		edit();
		AxilSet<T> s = new AxilSet<T>(this);
		for (T v : objects) {
			s.set.add(v);
		}
		return s;
	}


	/**
	 * Add the given value to this value, returning a new object. The given
	 * value is never null or nil. The value may be a numeric type of any other
	 * type of object that can sensibly implement the Added interface.
	 */
	public AxilObject add(AxilObject object) {
        if (object == Nil.object) {
            return Nil.object;
        }
        AxilSet<T> a = immutable ? cloned() : this;
        if (object instanceof AxilCollection) {
            a = a.put((AxilCollection<T>) object);
        } else {
            a = a.put((T) object);
        }
		return a.immute();
	}


	/**
	 * Subtract the given object from this object. The given value is never
	 * null or nil. The value may be a numeric type of any other type of object
	 * that can sensibly implement the Subtracted interface.
	 */
	public AxilObject subtract(AxilObject n) {
        if (n == Nil.object) {
            return Nil.object;
        }
        AxilSet<T> obj = immutable ? cloned() : this;
        Iterator<T> i = obj.set.iterator();
        if (n instanceof AxilCollection) {
            for (Object item : ((Iterable) n)) {
                while(i.hasNext()) {
                    if (i.next().equals((AxilObject) item)) {
                        // as a set, there should only be one.
                        i.remove();
                    }
                }

                i = obj.set.iterator();
            }
        } else {
            while(i.hasNext()) {
                if (i.next().equals(n)) {
                    // as a set, there should only be one.
                    i.remove();
                }
            }
        }
        return obj.immute();
    }


	/**
	 * Clone this object, returning a new object. The clone is sufficiently
	 * deep to ensure that any modifications to the clone, or to any member of
	 * the clone, do not impact this object.
	 */
	public AxilSet<T> cloned() {
		return new AxilSet<T>(this);
	}


	/**
	 * Mark this object as immutable, preventing any further changes. Any
	 * attempt to alter this collection after this point results in an exception.
	 */
	public AxilSet<T> immute() {
		immutable = true;
		return this;
	}


	private void edit() {
		if (immutable) {
            throw error(axil(), "immutable-object");
        }
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.
	 * Objects of incompatible types return a false value, not an exception.
	 */
    public boolean equalTo(AxilObject object) {
        if (! (object instanceof AxilCollection)) {
            return false;
        }
        if (size() != ((AxilCollection) object).size()) {
            return false;
        }
        Iterator ti = this.iterator();
        while(ti.hasNext()) {
            if (! ((AxilCollection) object).has((AxilObject) ti.next())) {
                return false;
            }
        }
        return true;
    }


	/**
	 * Get the size of this collection.
	 */
	public int size() {
		return set.size();
	}


	/**
	 * Returns an iterator over a set of elements of type T. The iterator
	 * returned does not allow for alteration of this collection.
	 */
	public Iterator<T> iterator() {
		return new Safe(set.iterator());
	}
}
